package huiji;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 攻击角色
 */
public class AttackObj extends BaseObj{
    protected List<Bullet> bullets = new ArrayList<>();
    protected int fireFrequence=100;//发射频率,每100毫秒
    protected long lastFireTime;//上次发射时间

    @Override
    public void paintOneOfList(Graphics g) {
        if(bullets.size()>0){
            bullets.stream().forEach(b->{b.paint(g);});
        }
        super.paintOneOfList(g);

    }

    /**
     * 发射子弹
     */
    public void fireBullet(){
        //现有子弹挪动或越界移除
        if(bullets.size()>0){
            for (int i =bullets.size()-1;i>=0;i-- ){
                Bullet b = bullets.get(i);
                if(b.isOut()){//子弹越界就删除
                    bullets.remove(i);
                    continue;
                }else{
                    b.setY(b.getY()-b.getSpeed());
                }
                //是否摧毁敌机
                for(int j = Enemy.enemies.size()-1;j>=0;j--){
                    if (b.touch(Enemy.enemies.get(j))){
                        Enemy.enemies.remove(j);
                        bullets.remove(i);
                        break;
                    }
                }
            }
        }
        //发射新子弹
        long now = System.currentTimeMillis();
        if (now-lastFireTime>=fireFrequence){
            bullets.add(createBullet());
            lastFireTime = now;
        }
        //System.out.println(bullets.size());

    }

    public Bullet createBullet(){
        return new Bullet().setImageAndWH(ImageUtil.gainImage("bullet.png"));
    }
}
